var lockReconnect = false;//避免重复连接
var wsUrl = "ws://127.0.0.1:8282";
var ws;
var tt;
var reconnectnum = 0;
const reconnectmax = 3;
var WebSocket_data = {}

function createWebSocket() {
    try {
        ws = new WebSocket(wsUrl);
        init();
    } catch (e) {
        reconnect(wsUrl);
    }
}

function init() {
    ws.onclose = function (e) {
        console.log('链接关闭');
        reconnect(wsUrl);
    };
    ws.onerror = function (e) {
        console.log('发生异常了');
        reconnect(wsUrl);
    };
    ws.onopen = function () {
        reconnectnum = 0;
        layer.close(loading)
        console.log('连接')
        //心跳检测重置
        heartCheck.start();
    };
    ws.onmessage = function (event) {
        //拿到任何消息都说明当前连接是正常的
        wsmessage(event.data)
        heartCheck.start();
    }
}

function reconnect(url) {
    if (lockReconnect) {
        return;
    }
    ;
    loading = layer.open({
        type: 2,
        content: '重连中，请等待',
        shadeClose: false,
    });
    dplayer.notice('你已断线,尝试重连中')
    if (reconnectnum >= reconnectmax) {
        layer.open({
            content: '你已经断开连接，请刷新页面'
            , btn: ['刷新', '退出']
            , shadeClose: false
            , yes: function (index) {
                window.location.replace(window.location.href);
            }
            , no: function (index) {
                history.back();
            }
        });
        dplayer.notice('你已断开，请刷新页面尝试重新连接')
        // mylayer.msg('重连过多，请重进房间');
        return false;
    }
    reconnectnum++;
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    tt && clearTimeout(tt);
    tt = setTimeout(function () {
        layer.close(loading)
        createWebSocket(url);
        lockReconnect = false;
    }, 4000);
}

//心跳检测
var heartCheck = {
    timeout: 30000,
    timeoutObj: null,
    start: function () {
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.timeoutObj = setTimeout(function () {
            ws.send(JSON.stringify({type: 'ping'}))
        }, this.timeout)
    }
}
// ws = new WebSocket(wsUrl);

createWebSocket();

function wsmessage(data) {
    data = JSON.parse(data)
    eval(data.type + '_ws(data)')
}

/** ping */
function ping_ws(data) {
}

/** 绑定uid,加入房间 */
function binduid_ws(data) {
    WebSocket_data.client_id = data.client_id
    mpostend('/index.php/index/play/binduid', {client_id: data.client_id}, function (res) {
        var userinfo = res.data.userinfo
        if (autojoin) {
            mpostend('/index.php/index/room/join/' + roomId, {
                password: '',
                client_id: WebSocket_data.client_id
            }, function (res) {
                ws.send(JSON.stringify({type: 'init', roomid: roomId, fromid: 0, toid: 0, reqtime: 0}))
                if (res.data.roominfo.owner_id == userinfo.id) {
                    content.master = 1
                    room.master = 1
                    dplayer.setControls({
                        next: true,
                        play: '',
                        wrap: '',
                    })
                }
            });
        }
    });

}

/** 成员退出房间 */
function menberExit_ws(data) {

}

/** 成员加入房间 */
function menberJoin_ws(data) {

}

/** 切换房主 */
function ownerExit_ws(data) {
    mylayer.msg('您已成为房主了')
    dplayer.notice('您已成为房主了')
    content.master = 1
    room.master = 1
    dplayer.setControls({
        next: true,
        play: '',
        wrap: '',
    })
}

/************  播放器操作    *********/
function isowner() {
    if (content.master == 1) {
        return true
    }
    return false
}

function init_ws(data) {
    if (!isowner()) {
        ws_send({type: 'synchro_playlist_req'}, false);
    }
}

/** 播放 */
function play_ws(data) {
    if (!isowner()) {
        dplayer.play();
        data.reqtime = new Date().getTime();
        data.playstatus = 'play'
        canplayinfo = data;
    }
}

/** 暂停 */
function pause_ws(data) {
    if (!isowner()) {
        dplayer.pause();
        data.reqtime = new Date().getTime();
    }
}

/** 进度变化 */
function seeked_ws(data) {
    if (!isowner()) {
        let seeked = Math.floor(data.currentTime)+1
        dplayer.seek(seeked);
        eval('dplayer.'+data.playstatus+"()")
    }
}

/** 全员进度同步 */
function synchro_seeked_group_ws(data) {
    if (!isowner()) {
        if (data.playing.url != content.playing.url) {
            data.reqtime = new Date().getTime();
            canplayinfo = data;
            content.playing = data.playing
            dplayer.switchVideo({
                url: data.playing.url
            })
        } else {
            let seeked =  Math.floor(data.currentTime)+1
            dplayer.seek(seeked);
        }
    }
}

/** 进度同步请求处理 */
function synchro_seeked_req_ws(data) {
    if (isowner()) {
        let playing = content.playing;
        let currentTime = dplayer.video.currentTime + ''
        ws_send({
            type: 'synchro_seeked_rep',
            toid: data.fromid,
            currentTime: currentTime,
            playing: playing,
            playstatus: content.playstatus
        })
    }
}

/** 进度同步响应处理 */
function synchro_seeked_rep_ws(data) {
    if (!isowner()) {
        if (data.playing.url != content.playing.url) {
            data.reqtime = new Date().getTime();
            canplayinfo = data;
            content.playing = data.playing
            dplayer.switchVideo({
                url: data.playing.url
            })
        } else {
            let seeked = Math.floor(data.currentTime)+1;
            eval('dplayer.'+data.playstatus+"()")
            dplayer.seek(seeked);
        }
    }
}

/** 播放列表同步请求 */
function synchro_playlist_req_ws(data) {
    if (isowner()) {
        ws_send({type: 'synchro_playlist_rep', toid: data.fromid, playlist: content.playlist, playing: content.playing})
    }
}

/** 播放列表同步响应 */
function synchro_playlist_rep_ws(data) {
    if (!isowner()) {
        content.playlist = data.playlist
        if (data.playing.url != content.playing.url) {
            ws_send({type: 'synchro_seeked_req'}, false);
        }
    }
}
